import java.sql.Array;
import java.util.ArrayDeque;
import java.util.Deque;

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    public boolean isValidBST(TreeNode root) {
        return isValid(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
    }

    boolean isValid(TreeNode root, int min, int max) {
        if (root == null) {
            return true;
        }

        //防越界。或使用long
        if (root.val == Integer.MIN_VALUE && root.left != null) {
            return false;
        }
        if (root.val == Integer.MAX_VALUE && root.right != null) {
            return false;
        }

        return root.val >= min && root.val <= max
                && isValid(root.left, min, root.val - 1) && isValid(root.right, root.val + 1, max);
    }
}

//中序遍历
class Solution1 {
    public boolean isValidBST(TreeNode root) {
        Deque<TreeNode> stack = new ArrayDeque<>();
        TreeNode cur = root;
        Integer prevVal = null;
        while (cur != null || !stack.isEmpty()) {
            if (cur != null) {
                stack.push(cur);
                cur = cur.left;
            } else {
                cur = stack.pop();
                if (prevVal != null && cur.val <= prevVal) {
                    return false;
                }
                prevVal = cur.val;
                cur = cur.right;
            }
        }
        return true;
    }
}